<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="配件名称" prop="partName">
        <el-input
          v-model="queryParams.partName"
          placeholder="请输入配件名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="配件分类" prop="partKindId">
        <el-input
          v-model="queryParams.partKindId"
          placeholder="请输入配件分类"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="配件类型" prop="partTypeId">
        <el-input
          v-model="queryParams.partTypeId"
          placeholder="请输入配件类型英文逗号分割"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="原价" prop="oldPrice">
        <el-input
          v-model="queryParams.oldPrice"
          placeholder="请输入原价"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="现价" prop="nowPrice">
        <el-input
          v-model="queryParams.nowPrice"
          placeholder="请输入现价"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="打折" prop="partOff">
        <el-input
          v-model="queryParams.partOff"
          placeholder="请输入打折"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="库存" prop="partLast">
        <el-input
          v-model="queryParams.partLast"
          placeholder="请输入库存"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="售出" prop="partSaled">
        <el-input
          v-model="queryParams.partSaled"
          placeholder="请输入售出"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="体积" prop="partVolume">
        <el-input
          v-model="queryParams.partVolume"
          placeholder="请输入体积"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="重量" prop="partWeight">
        <el-input
          v-model="queryParams.partWeight"
          placeholder="请输入重量"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否原装" prop="isOri">
        <el-select clearable v-model="queryParams.isOri" placeholder="是否原装" clearable size="small">
          <el-option
            v-for="dict in yesOrNo"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用车类型" prop="carTypeId">
        <el-select clearable v-model="queryParams.carTypeId" placeholder="是否原装" clearable size="small">
          <el-option
            v-for="dict in carTypeIdOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="品牌logo" prop="carLogoId">
         <el-input
           v-model="queryParams.carLogoId"
           placeholder="请输入品牌logo"
           clearable
           size="small"
           @keyup.enter.native="handleQuery"
         />
       </el-form-item>-->
      <el-form-item label="上架时间" prop="upDatetime">
        <el-date-picker clearable size="small" style="width: 200px"
                        v-model="queryParams.upDatetime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择上架时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="快递费" prop="postPay">
        <el-input
          v-model="queryParams.postPay"
          placeholder="请输入快递费"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select clearable v-model="queryParams.status" placeholder="状态" clearable size="small">
          <el-option
            v-for="dict in yesOrNo"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['shop:part:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['shop:part:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['shop:part:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['shop:part:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="partList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--<el-table-column label="配件图片，多张图片，英文逗号分割" align="center" prop="partPic" />-->
      <el-table-column label="配件名称" align="center" prop="partName"/>
      <el-table-column label="配件分类" align="center" prop="partKindId"/>
      <el-table-column label="所属商家" align="center" prop="shopName"/>
      <!--<el-table-column label="配件类型英文逗号分割" align="center" prop="partTypeId" />-->
      <el-table-column label="原件" align="center" prop="oldPrice"/>
      <el-table-column label="现价" align="center" prop="nowPrice"/>
      <el-table-column label="打折" align="center" prop="partOff"/>
      <el-table-column label="库存" align="center" prop="partLast"/>
      <el-table-column label="售出" align="center" prop="partSaled"/>
      <el-table-column label="品牌名" align="center" prop="logoName"/>
      <!-- <el-table-column label="体积" align="center" prop="partVolume" />
       <el-table-column label="重量" align="center" prop="partWeight" />-->
      <el-table-column label="是否原装" align="center" prop="isOri" :formatter="yesOrNoFormat"/>
      <el-table-column label="用车类型" align="center" prop="carTypeId" :formatter="carTypeIdFormat"/>
      <el-table-column label="上架时间" align="center" prop="upDatetime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.upDatetime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="快递费" align="center" prop="postPay" />
       <el-table-column label="配件详情" align="center" prop="partInfo" />
       <el-table-column label="状态" align="center" prop="status" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['shop:part:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['shop:part:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商户配件对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="商铺id" prop="shopId">
           <el-input v-model="form.shopId" placeholder="请输入商铺id" />
         </el-form-item>-->
        <el-form-item label="配件名称" prop="partName">
          <el-input v-model="form.partName" placeholder="请输入配件名称"/>
        </el-form-item>
        <el-form-item label="配件图片" prop="partPic">
          <el-upload
            v-model="form.partPic"
            :action="upload.url"
            :headers="upload.headers"
            list-type="picture-card"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="配件分类" prop="partKindId">
          <treeselect v-model="form.partKindId" :options="kindOptions" :normalizer="normalizer" placeholder="请选择父id" />
        </el-form-item>
        <el-form-item label="配件类型" prop="partTypeList">
          <el-select multiple v-model="form.partTypeList" clearable placeholder="请选择">
            <el-option
              v-for="dict in partType"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="原件" prop="oldPrice">
          <el-input v-model="form.oldPrice" placeholder="请输入原件"/>
        </el-form-item>
        <el-form-item label="现价" prop="nowPrice">
          <el-input v-model="form.nowPrice" placeholder="请输入现价"/>
        </el-form-item>
        <el-form-item label="打折" prop="partOff">
          <el-input v-model="form.partOff" placeholder="请输入打折"/>
        </el-form-item>
        <el-form-item label="库存" prop="partLast">
          <el-input v-model="form.partLast" placeholder="请输入库存"/>
        </el-form-item>
        <el-form-item label="售出" prop="partSaled">
          <el-input v-model="form.partSaled" placeholder="请输入售出"/>
        </el-form-item>
        <el-form-item label="体积" prop="partVolume">
          <el-input v-model="form.partVolume" placeholder="请输入体积"/>
        </el-form-item>
        <el-form-item label="重量" prop="partWeight">
          <el-input v-model="form.partWeight" placeholder="请输入重量"/>
        </el-form-item>
        <el-form-item label="是否原装">
          <el-select v-model="queryParams.isOri" placeholder="是否原装" clearable size="small">
            <el-option
              v-for="dict in yesOrNo"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用车类型" prop="carTypeId">
          <el-select v-model="queryParams.carTypeId" placeholder="请输入用车类型" clearable size="small">
            <el-option
              v-for="dict in carTypeIdOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="品牌logo" prop="carLogoId">
          <treeselect v-model="form.carLogoId" :options="logoOptions" :normalizer="normalizerCar" placeholder="请选择" />
        </el-form-item>
        <el-form-item label="车型" prop="carLogocarId">
          <treeselect v-model="form.carLogocarId" :options="logocarOptions" :normalizer="normalizerCar" placeholder="请选择" />
        </el-form-item>
        <el-form-item label="快递费" prop="postPay">
          <el-input v-model="form.postPay" placeholder="请输入快递费"/>
        </el-form-item>
        <el-form-item label="发货地" prop="postAddress">
          <el-input v-model="form.postAddress" placeholder="请输入快递费"/>
        </el-form-item>
        <el-form-item label="产地" prop="makeAddress">
          <el-input v-model="form.makeAddress" placeholder="请输入快递费"/>
        </el-form-item>
        <el-form-item label="商品评价" prop="partRate">
          <el-input v-model="form.partRate" placeholder="请输入快递费"/>
        </el-form-item>
        <el-form-item label="配件详情">
          <editor v-model="form.partInfo" :min-height="192"/>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio label="1">请选择字典生成</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listPart, getPart, delPart, addPart, updatePart, exportPart} from "@/api/shop/part";
import Editor from '@/components/Editor';
import {getToken} from "@/utils/auth";
import {listKind} from "@/api/shop/kind";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {listLogo} from "@/api/shop/logo";
export default {
  name: "Part",
  components: {Editor,Treeselect},
  data() {
    return {
      picProxy: process.env.VUE_APP_BASE_API.replace('/',''),
      dialogImageUrl: '',
      dialogVisible: false,
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload",
        // 上传的文件列表
        fileList: []
      },
      // 配件分类树选项
      kindOptions: [],
      logoOptions: [],
      logocarOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商户配件表格数据
      partList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 配件类型字典
      partType: [],
      // 用车类型字典
      carTypeIdOptions: [],
      yesOrNo: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        shopId: null,
        partName: null,
        partPic: null,
        partKindId: null,
        partTypeId: null,
        partTypeList: [],
        oldPrice: null,
        nowPrice: null,
        partOff: null,
        partLast: null,
        partSaled: null,
        partVolume: null,
        partWeight: null,
        isOri: null,
        carTypeId: null,
        carLogoId: null,
        postAddress: null,
        makeAddress: null,
        partRate: null,
        upDatetime: null,
        postPay: null,
        partInfo: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.getList();
    this.getDicts("carparts_usecar").then(response => {
      this.carTypeIdOptions = response.data;
    });

    this.getDicts("carparts_yes_no").then(response => {
      this.yesOrNo = response.data;
    });

    this.getDicts("carparts_type").then(response => {
      this.partType = response.data;
    });
    this.getTreeselect();
  },
  methods: {
    getTreeselect() {
      listLogo().then(response => {
        this.logoOptions = [];
        this.logocarOptions = [];
        const data = { logoId: 0, name: '顶级节点', children: [] };
        const dataCar = { logoId: 0, name: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "logoId", "pid");
        dataCar.children = this.handleTree(response.data, "logoId", "pid");
        this.logoOptions.push(data);
        this.logocarOptions.push(dataCar);
      });
      listKind().then(response => {
        this.kindOptions = [];
        const data = { partKindId: 0, kindName: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "partKindId", "pid");
        this.kindOptions.push(data);
      });
    },
    normalizerCar(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.logoId,
        label: node.name,
        children: node.children
      };
    },
    /** 转换配件分类数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.partKindId,
        label: node.kindName,
        children: node.children
      };
    },
    //图片墙
    handleAvatarSuccess(res, file) {
      this.upload.fileList.push(res.fileName)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    handleRemove(file, fileList) {
      this.upload.fileList.splice(this.upload.fileList.findIndex(item => item === file.response.fileName), 1)
      // alert(JSON.stringify(this.upload.fileList))
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    /** 查询商户配件列表 */
    getList() {
      this.loading = true;
      listPart(this.queryParams).then(response => {
        this.partList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 用车类型字典翻译
    carTypeIdFormat(row, column) {
      return this.selectDictLabel(this.carTypeIdOptions, row.carTypeId);
    },
    yesOrNoFormat(row, column) {
      return this.selectDictLabel(this.yesOrNo, row.carTypeId);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        partId: null,
        shopId: null,
        partName: null,
        partPic: null,
        partKindId: null,
        partTypeId: null,
        oldPrice: null,
        nowPrice: null,
        partOff: null,
        partLast: null,
        partSaled: null,
        partVolume: null,
        partWeight: null,
        isOri: "0",
        carTypeId: null,
        carLogoId: null,
        carLogocarId: null,
        upDatetime: null,
        postPay: null,
        partInfo: null,
        status: "0",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.partId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商户配件";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const partId = row.partId || this.ids
      getPart(partId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商户配件";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // alert(JSON.stringify(this.upload.fileList))
          this.form.partPic = '';
          this.upload.fileList.map(v=>{
            this.form.partPic = this.form.partPic + v +','
          })
          this.form.partPic = this.form.partPic.substr(0,this.form.partPic.length-1);
          this.form.partTypeId = '';
          this.form.partTypeList.map(v=>{
            this.form.partTypeId = this.form.partTypeId + v+','
          })
          this.form.partTypeId = this.form.partTypeId.substr(0,this.form.partTypeId.length-1);

          if (this.form.partId != null) {
            updatePart(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPart(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const partIds = row.partId || this.ids;
      this.$confirm('是否确认删除商户配件编号为"' + partIds + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delPart(partIds);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有商户配件数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return exportPart(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    }
  }
};
</script>
